package com.itheima;

import java.util.Comparator;
import java.util.TreeSet;

public class TreeSetDemo {
    public static void main(String[] args) {
       // TreeSet集合只能存储引用数据类型
        TreeSet<Integer> set1 = new TreeSet<>(); //key
        //TreeSet集合存储数据时，会自动按照从小到大的顺序进行排序
        //包装成Integer对象，存储到TreeSet集合中
        set1.add(1);
        set1.add(2);
        set1.add(5);
        set1.add(4);
        set1.add(3);

        System.out.println(set1);

        for(Integer integer : set1){
            System.out.println(integer);
        }
        test1();
        System.out.println("------------------------------");
        test2();
        System.out.println("------------------------------");
        System.out.println(sum(1,2,3,4));
    }

    public static void test1(){

        TreeSet<Student> set = new TreeSet<>();
        set.add(new Student("lh", 18));
        set.add(new Student("ly", 19));
        set.add(new Student("lyn", 17));
        set.add(new Student("lqw", 16));

        for(Student student : set){
            System.out.println(student.getName() + ":" + student.getAge());
        }
    }

    public static void test2(){
        Comparator<Student> comparator = new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                //  按照学生年龄的正序排序 o1 - o2
                //  按照学生年龄的倒序排序 o2 - o1
                return o2.getAge() - o1.getAge();
            }
        };
        TreeSet<Student> set = new TreeSet<>(comparator);

        set.add(new Student("lh", 18));
        set.add(new Student("ly", 19));
        set.add(new Student("lyn", 17));
        set.add(new Student("lqw", 16));

        for(Student student : set){
            System.out.println(student.getName() + ":" + student.getAge());
        }
        System.out.println("---------Lambda表达式-----------------------");
        Comparator<Student> comparator1 = (o1, o2)->  o1.getAge() - o2.getAge();//函数式子编程
        TreeSet<Student> set1 = new TreeSet<>(comparator1);
        set1.add(new Student("lh", 18));
        set1.add(new Student("ly", 19));
        set1.add(new Student("lyn", 17));
        set1.add(new Student("lqw", 16));
        for(Student student : set1){
            System.out.println(student.getName() + ":" + student.getAge());
        }
    }
    //可变参数必须是形参的最后一个
    public static int sum(int... a){//可变参数
        int total = 0;
        for(int i = 0; i < a.length; i++){
            total += a[i];
        }
        return total;
    }
}
